import React, {useRef, useState} from "react";
import {FormInstance} from "@ant-design/pro-form"
import {Form,ModalProps} from "antd";
import {ModalPermission} from "@/components/Permission";
import interfaceService from "@/services/interface";
import {FunctionInterfaceDTO, InterfaceVO} from "@/types/interface";
import {arrayToTree, transformParams} from "@/utils/utils";
import FormTable from "@/components/FormTable";
import {ProColumns, RequestData} from "@ant-design/pro-table";
import CustomTreeSelect from "@/components/CustomTreeSelect";
import {OptionType} from "@/types/common";
import functionService from "@/services/function";

interface InterfaceFormProps{
  params?:any;
  functionOptions?:OptionType[];
  onFinish?: (formData:any) => Promise<any | void>;
  /** @name 用于触发抽屉打开的 dom */
  trigger?: JSX.Element;
  /** @name 获取真正的可以获得值的 from */
  formRef?: React.MutableRefObject<(FormInstance & {
    getFieldsFormatValue?: () => any;
  }) | undefined>;
  onReset:()=>void;
  functionKey?:string;
  /** @name 打开关闭的事件 */
  onVisibleChange?: (visible: boolean) => void;
  /** @name 受控的打开关闭 */
  visible?: ModalProps['visible'];
}

const queryList= async (params:any, sorter:any, filter:any): Promise<RequestData<InterfaceVO>> => {
  if(params&&params.functionId){
    const  dto = transformParams(params, sorter);
    const response=await interfaceService.queryUnassignedList(dto);
    const {data}=response;
    const {pagination}=data;
    return {
      success:true,
      data:data.items,
      total:pagination.total || [],
    };
  }else{
    return {
      success:true,
      data:[],
      total:0,
    };
  }
}

const create= async (params:FunctionInterfaceDTO): Promise<InterfaceVO> => {
  const response=await interfaceService.createFunctionInterfaceRelation(params);
  return new Promise((resolve, reject) => {
    resolve(response);
  })
}

const columns: ProColumns<InterfaceVO>[] = [
  {
    title: '接口名称',
    align:'left',
    dataIndex: ['name'],
  },
  {
    title: '接口路径',
    align:'left',
    dataIndex: ['path'],
  },
  {
    title: '接口方法',
    align: 'center',
    dataIndex: ['method'],
  },
  {
    title: '接口类型',
    align: 'center',
    dataIndex: ['type'],
  }
];


const InterfaceForm:React.FC<InterfaceFormProps> = (props) =>{

  const formRef = useRef<FormInstance>();

  const [params,setParams]=useState<any>(props.params);

  const onFinish=async (values:any) => {
    return new Promise<boolean|void>((resolve, reject)=>{
      if(props.onFinish){
        props.onFinish(values)
          .then(({exception})=>{
            if(!exception){
              props.onReset();
              formRef.current?.resetFields();
              resolve(true);
            }else{
              reject();
            }
          });
      }
    })
  }

  const onChange=(value:any)=>{
    if(value){
      setParams([value])
    }else{
      setParams([])
    }
  }

  return (
    <ModalPermission
      formRef={formRef}
      functionKey={props.functionKey}
      visible={props.visible}
      onVisibleChange={props.onVisibleChange}
      trigger={props.trigger}
      onFinish={onFinish}
      initialValues={{
        ...props.params
      }}
      layout={"horizontal"}
      modalProps={{
        bodyStyle:{
          padding:56
        },
        title:'关联接口'
      }}
    >
      <Form.Item
        name={'functionId'}
        label="选择功能"
        rules={[
          {required:true,message:'请选择功能'}
        ]}
      >
        <CustomTreeSelect
          list={props.functionOptions}
          multiple={false}
          onChange={onChange}
        />
      </Form.Item>
      <Form.Item
        name="interfaceIds"
        label={'选择接口'}
        rules={[
          {required:true,message:'请选择接口'}
        ]}
      >
        <FormTable
          // @ts-ignore
          rowKey={((record) => record.id)}
          columns={columns}
          pagination={{
            pageSize:10,
            showTotal:(total => null),
            showSizeChanger:true,
            showQuickJumper:true,
          }}
          params={params}
          request={queryList}
        />
      </Form.Item>
    </ModalPermission>
  )
}

export const InterfaceCreateForm:React.FC<InterfaceFormProps> = (props) =>{
  const formRef = useRef<FormInstance>();

  const [functionOptions,setFunctionOptions] = useState<OptionType[]>([]);

  const onVisibleChange=(visible: boolean)=>{
    if(visible){
      functionService.queryList()
        .then(({data})=>{
          setFunctionOptions(arrayToTree(data));
        })
      formRef.current?.setFieldsValue({
        ...props.params
      })
    }
    if(props.onVisibleChange && !visible){
      props.onVisibleChange(visible);
    }
  }

  return (
    <InterfaceForm
      {...props}
      formRef={formRef}
      functionOptions={functionOptions}
      onFinish={create}
      onVisibleChange={onVisibleChange}
    />
  )
}

